// HSR.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "HSR.h"

#include "dibapi.h"
#include "hsr_core.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

#define DATABASE_NAME _T("hsr.db")


// The one and only application object
CWinApp theApp;

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
	int nRetCode = 0;
	CFile file;

	// initialize MFC and print and error on failure
	if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
	{
		// TODO: change error code to suit your needs
		_tprintf(_T("Fatal Error: MFC initialization failed\n"));
		nRetCode = 1;
	}
	else if (argc < 3)
	{
		_tprintf(_T("Fatal Error: please supply file name and image class\n"));
		nRetCode = 2;
	}
	else if (!file.Open(argv[1], CFile::modeRead))
	{
		_tprintf(_T("Fatal Error: couldn't open file: %s\n"), argv[1]);
		nRetCode = 3;
	}
	else 
	{
		Database database(DATABASE_NAME);

		HDIB dib = ReadDIBFile(file);
		file.Close();

		BYTE* lpS = (BYTE*)::GlobalLock((HGLOBAL)dib);
		BYTE* lpSrc = (BYTE*)::FindDIBBits((LPSTR)lpS);
		DWORD dwWidth  = ::DIBWidth((LPSTR)lpS);
		DWORD dwHeight = ::DIBHeight((LPSTR)lpS);
		DWORD w=WIDTHBYTES(dwWidth*8);

		Contour contour;
		if (!contour_extract(contour, dwWidth, dwHeight, w, lpSrc))
		{
			_tprintf(_T("Error: couldn't extract contour\n"));
			nRetCode = 4;
		}
		else
		{
			// transformata Fourier
			FourierSerie fourier_serie;
			for (unsigned int u = 0; u < 20; u++)
			{
				FourierTerm t = dft(contour, u);
				fourier_serie.push_back(t);
			}

			for (unsigned int u = contour.size() - 20; u < contour.size(); u++)
			{
				FourierTerm t = dft(contour, u);
				fourier_serie.push_back(t);
			}

			//database.GetList().push_back(fourier_serie);
			//for (unsigned int k = 0; k < contour.size(); k++)
			//{
			//	Point p = idft(fourier_serie, k);
			//}

			Centroid *centroid;
			CentroidList &centroid_list = database.centroid_list();

			if (centroid_search(centroid_list, argv[2], &centroid))
			{
				*centroid << fourier_serie;
			}
			else
			{
				Centroid new_centroid;
				new_centroid.label = argv[2];
				new_centroid << fourier_serie;
				centroid_list.push_back(new_centroid);
			}

			fourier_serie.clear();
			contour.clear();

			::GlobalUnlock((HGLOBAL)dib);

			nRetCode = 0;
		}
	}

	return nRetCode;
}
